package nirvana.core.security;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import nirvana.core.context.WebContext;


import nirvana.core.properties.SecurityProperties;
import nirvana.core.utils.JwtTools;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author linkanyway
 * @version 1.0
 * @description TODO
 * @date 2021/09/20 13:50
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private final String USER_STATUS_KEY = "USER_STATUS_KEY";

    private final SecurityProperties securityProperties;


    private final RedisTemplate<String, Integer> integerRedisTemplate;

    public AuthInterceptor(SecurityProperties securityProperties, RedisTemplate<String, Integer> integerRedisTemplate) {
        this.securityProperties = securityProperties;
        this.integerRedisTemplate = integerRedisTemplate;
    }

    /**
     * @param request  http request
     * @param response http response
     * @param handler  handler
     * @return result
     * @throws Exception
     * @// TODO: 2021/9/20  ready to implement logic
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        /*
        校验token逻辑
        并从token中获取用户信息
         */
        //获取token
        String tokenHttpHeader = securityProperties.getTokenHttpHeader();
        String token = request.getHeader(tokenHttpHeader);

        if (!StringUtils.hasText(token) || !token.startsWith(securityProperties.getTokenHead())) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        token = token.substring(securityProperties.getTokenHead().length() + 1);

        SecurityCredential credential = JwtTools.getUserInfoFromToken(token);

        /**
         * 解析不出或为空、为refreshToken时，返回401
         */
        if (credential == null || null == credential.getIsRefresh() || credential.getIsRefresh()) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        //检查用户是否为启用状态
        Long userId = credential.getId();
        HashOperations<String, String, Integer> hash = integerRedisTemplate.opsForHash();
        Integer status = hash.get(USER_STATUS_KEY, userId.toString());
        if (status != null && status != 1) {
            return false;
        }


        //  设置用户信息
        WebContext.remove();
        WebContext.setThreadPrincipal(credential);


        // setup session id
        Long id = IdGenerator.SNOW.generate();
        System.out.println("设置RequestId为" + id);
        WebContext.setRequestId(id);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * @param request      http request
     * @param response     http response
     * @param handler      handler
     * @param modelAndView model and view
     * @throws Exception exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}